<template>
  <div>
    <div class="data">
      <el-table :data="list.text" border>
        <el-table-column
          v-for="(value, key, index) in list.head"
          :key="key"
          :index="index"
          :prop="key"
          :label="value"
          width="180"
        >
          <!--  template 不能使用v-if  v-for和v-if不能同时使用-->
          <template slot-scope="scope">
            <div v-if="list.text[scope.$index][key]">
              <p>{{ list.text[scope.$index][key] }}</p>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
   
    <!--  excel表格上传 start -->
    <!-- action是上传文件的接口 -->
    <el-upload
      class="upload-demo"
      drag
      action="http://47.106.246.177:8080/form/upload"
      multiple
      accept=".xls,.xlsx"
      :on-exceed="exceed"
      :limit="1"
      :on-remove="remove"
      :http-request="uploadFile"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div class="el-upload__tip" slot="tip">
        1次只能上传1个xls文件，且不超过500kb
      </div>
    </el-upload>
    <!--  excel表格上传 end -->
  </div>
</template>

<script>
import { importExcel } from "../../../network/index";
import XLSX from "xlsx";
export default {
  data() {
    return {
      listTable: [],
      // 展示的数据
      list: {
        text: [],
      },
    };
  },
  methods: {
    //解析excel
    async uploadFile(params) {
      const _file = params.file;
      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary",
          });
          for (let sheet in workbook.Sheets) {
            //循环读取每个文件
            const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
            //若当前sheet没有数据，则continue
            if (sheetArray.length == 0) {
              continue;
            }
            // console.log("读取文件");
            // console.log(sheetArray);
            this.listTable = sheetArray;
          }
          //   发送数据给后端
          importExcel({ data: this.listTable }).then((res) => {
            if (res != null) {
              this.$message({
                message: "恭喜你，导入数据成功",
                type: "success",
              });
              this.list = res.data;
              // console.log(res.data);
            } else {
              this.$message.error("错了哦，导入数据失败,请重新导入!");
            }
          });

          //   console.log(this.listTable);
        } catch (e) {
          this.$message.warning("文件类型不正确！");
        }
      };
      fileReader.readAsBinaryString(_file);
    },
    //上传1个以上文件时弹窗提示错误
    exceed: function () {
      this.$message.error("最多只能上传1个xls文件");
    },
    //删除文件
    remove() {
      this.listTable = [];
    },
  },
};
</script>
<style scoped>
</style>